package org.mc.config;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;

@Configuration
@Slf4j
public class EsConfig {

    @Autowired(required = false)
    private ElasticSearchConfig config;

    /*@Bean
    public Client create() throws UnknownHostException {
        Settings settings = Settings.builder().put("cluster.name", config.getClusterName())
                .put("xpack.security.transport.ssl.enabled", false)
                .put("xpack.security.user", config.getAccount() + ":" + config.getPasswd())
                .put("client.transport.sniff", false).build();
        try {
            TransportClient client = new PreBuiltXPackTransportClient(settings);
            for (String url : config.getUrl()) {
                client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(url), 9300));
            }
            return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }*/

    @Bean
    public Client create() {
        try {
            TransportClient client = new PreBuiltXPackTransportClient(Settings.builder()
                    .put("cluster.name", config.getClusterName())
                    .put("xpack.security.user", config.getAccount() + ":" + config.getPasswd())
                    .put("client.transport.sniff", false)
                    .build())
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(config.getUrl()), 9300));
            log.info("ElasticsearchClient 连接成功!!!");
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}